package com.base.cn.platform.os.interceptor;

import com.base.cn.platform.os.common.reqToken.ReqTokenTools;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求Token拦截
 *
 * @author s.li
 * @date 2019/02/16
 */
@Component
@Slf4j
public class RequestTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private ReqTokenTools reqTokenTools;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String parameter = WebUtils.getRequestParameter(request);
        String url = request.getRequestURL().toString();
        String token = WebUtils.getCookie(request,ReqTokenTools.webKey);
        log.info("=============token:"+token+",url:"+url);
        if(!StringUtils.isNotEmpty(token)){
            reqTokenTools.genToken(request,response,ReqTokenTools.WEB);
            response.sendRedirect(url+"?"+parameter);
            return false;
        }
        //验证再请求的Token
        boolean status = reqTokenTools.validateToken(token);
        if(!status){
            reqTokenTools.cleanReqToken(request,response,token,ReqTokenTools.WEB);
            response.sendRedirect("/web/webError");
            return false;
        }
        //重新生成
        reqTokenTools.genToken(request,response,ReqTokenTools.WEB);
        return true;
    }
}
